﻿
// 对layui表格进行全局设置
function layuiTableSet() {
    if (layui.setter == undefined || layui.table == undefined) {
        layer.msg("表格初始化配置应用失败！请检查你的代码！", { icon: 2 });
    }

    var table_set = {
        headers: { 'Authorization': "Bearer " + layui.setter.getToken().JwtToken },
        request: {
            pageName: 'PageIndex' //页码的参数名称，默认：page
            , limitName: 'PageSize' //每页数据量的参数名，默认：limit
        },
        limit: 15,
        limits: [15, 30, 45, 60],
        response: {
            statusName: 'Tag' //规定数据状态的字段名称，默认：code
            , statusCode: 1 //规定成功的状态码，默认：0
            , msgName: 'Message' //规定状态信息的字段名称，默认：msg
            , countName: 'Total' //规定数据总数的字段名称，默认：count
            , dataName: 'Data' //规定数据列表的字段名称，默认：data
        },
        done: function () {
            // 校验权限，如果done被重写了，记得加这个方法
            CheckButtonAuthority();
        }
    };

    // 根据高度判断表格应该显示多少
    var height = $(window).height();
    if (height > 900) {
        table_set.height = 'full-160';
        table_set.limit = 20;
        table_set.limits = [20, 30, 40, 50, 60, 70, 80, 90, 100];
    } else {
        table_set.height = 'full-133';
        table_set.limit = 15;
        table_set.limits = [15, 30, 45, 60];
    }

    layui.table.set(table_set);
}

// 针对表格按钮的权限验证
function CheckButtonAuthority() {

    // 校验按钮权限，没有权限的按钮就隐藏
    if (GetButtonAuthority()) {
        var buttonList = [];
        $('.layui-table-tool-temp').find('a').each(function (i, ele) {
            buttonList.push(ele.id);
        });
        var removeButtonList = GetButtonAuthority(window.location.href, buttonList);
        if (removeButtonList) {
            $.each(removeButtonList, function (i, val) {
                $("#" + val).remove();
            });
        }
    }
}
// 取出需要的权限信息
function GetButtonAuthority(url, buttonList) {
    var noAuthorize = [];
    var dataAuthority = layui.sessionData('dataAuthority').dataAuthority;

    if (dataAuthority) {
        // 超级用户不验证
        if (dataAuthority.IsSystem != 1) {
            var regex = /([a-zA-Z]+)\/(.*)\//;  //match url like http://localhost:5000/OrganizationManage/User/UserIndex

            if (url) {
                url = url.replace(/Manage\//, "/");
                // 根据视图存放位置，切割后面的主要字符串
                var t = url.split(viewPath);
                url = t[t.length - 1];
            }

            var matches = regex.exec(url);
            if (matches && matches.length >= 3) {
                var module = matches[1];
                var page = matches[2];
                buttonList.forEach(function (btn, btnIndex) {
                    var authorize = module.toLowerCase() + ':' + page.toLowerCase() + ':' + btn.toString().replace('btn', '').toLowerCase();
                    var hasAuthority = false;

                    dataAuthority.MenuAuthorize.forEach(function (authority, authorityIndex) {
                        if (authority.Authorize == authorize) {
                            hasAuthority = true;
                            return false;
                        }
                    });

                    if (!hasAuthority) {
                        noAuthorize.push(btn);
                    }
                });
            }
        }
    } else {
        top.window.location.reload();
    }
    return noAuthorize;
}


// 获取get字段
function getRequestData(name) {
    var params = decodeURI(window.location.search);
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = params.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

/**
 * 初始化 layui 复选框 form模块，div id名称，name 复选框name， arr数组：[{Key:1,Value:1}]
 * @param {any} form
 * @param {any} id
 * @param {any} name
 * @param {any} arr
 * @param {any} keyName
 * @param {any} valueName
 */
function setLayuiCheckbox(form, id, name, arr, keyName, valueName) {
    var h = [];
    for (var i = 0; i < arr.length; i++) {
        var a = arr[i];
        h.push('<input type="checkbox" name="');
        h.push(name);
        h.push('" title="');

        if (keyName) {
            h.push(a[keyName]);
        } else {
            h.push(a.Key);
        }

        h.push('" value="');

        if (valueName) {
            h.push(a[valueName]);
        } else {
            h.push(a.Value);
        }

        h.push('"  lay-filter="');
        h.push(name);
        h.push('" lay-skin="primary"> ');
    }

    var str = h.join('');
    if (id.substr(0, 1) == "#") {
        $(id).html(str);
    } else {
        $("#" + id).html(str);
    }

    form.render('checkbox'); //刷新select选择框渲染
}

//xmSelect序列化数据
function listToTree(data) {
    let arr = JSON.parse(JSON.stringify(data))
    const listChildren = (obj, filter) => {
        [arr, obj.children] = arr.reduce((res, val) => {
            if (filter(val))
                res[1].push(val)
            else
                res[0].push(val)
            return res
        }, [[], []])
        obj.children.forEach(val => {
            if (arr.length)
                listChildren(val, obj => obj.pId === val.id)
        })
    }
    const tree = {}
    listChildren(tree, val => arr.findIndex(i => i.id === val.pId) === -1)
    return tree.children
}

/**
 * 递归获取树形数组的值（键值为value）
 * @param {any} Arr
 * @param {any} ID
 */
function findTreeId(Arr, ID) {
    var _result = null;
    for (let i = 0; i < Arr.length; i++) {
        //console.log(Arr[i], Arr[i].id == ID)
        if (Arr[i].value == ID) return Arr[i];
        if (Arr[i].children) _result = findTreeId(Arr[i].children, ID)
        if (_result != null) return _result;
    }
    return _result
}

/**
 * 根据字符串返回区域的描述
 * Ids: 34,3413,341322,341322102,341322102003
 */
function findAreaStr(Arr, Ids) {

    if (!Ids) return '-';

    var ids = Ids.split(',');
    var res = [];
    for (var i = 0; i < ids.length; i++) {
        var t = findTreeId(Arr, ids[i]);
        res.push(t.label);
    }

    return res.join('-');
}

/****************
 * 获取当前时间，并格式化为"yyyy-MM-dd HH:mm:ss" 
 ****************/
function getFormatDate() {
    var date = new Date();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentDate = date.getFullYear() + "-" + month + "-" + strDate
        + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return currentDate;
}